#include "ColorRenderTarget.h"

ColorRenderTarget::ColorRenderTarget(unsigned int width, unsigned int height) {
	width_ = width;
	height_ = height;


	glGenTextures(1, &col_textureID_);
	glBindTexture(GL_TEXTURE_2D, col_textureID_);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexImage2D(
		GL_TEXTURE_2D,
		0,
		GL_RGBA8,
		width_,
		height_,
		0,
		GL_BGRA,
		GL_UNSIGNED_BYTE,
		0);

	glGenFramebuffersEXT(1, &frameBufferID_);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBufferID_);
        
	glFramebufferTexture2DEXT(
		GL_FRAMEBUFFER_EXT,
		GL_COLOR_ATTACHMENT0_EXT,
		GL_TEXTURE_2D,
		col_textureID_,
		0);

	//-------------------------
	glGenRenderbuffersEXT(1, &depthBufferID_);
	glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthBufferID_);
	glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, width_, height_);
	//-------------------------
	//Attach depth buffer to FBO
	glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depthBufferID_);
	//-------------------------

	if (GL_FRAMEBUFFER_COMPLETE_EXT != glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT)) {
		printf("Invalid framebuffer configuration\n");
		//exit(-1);
	}
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	//glDrawBuffer(GL_BACK);
	glBindTexture(GL_TEXTURE_2D, 0);
}

ColorRenderTarget::~ColorRenderTarget() {
	
	glDeleteTextures(1, &col_textureID_);
	glDeleteRenderbuffersEXT(1, &depthBufferID_);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	glDeleteFramebuffersEXT(1, &frameBufferID_);

}

GLuint ColorRenderTarget::colorTextureID() const {
	return col_textureID_;
}


void ColorRenderTarget::bind() {
	//glPushAttrib(GL_VIEWPORT_BIT);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBufferID_);
	//glViewport(0, 0, width_, height_);
}

void ColorRenderTarget::unbind() {
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	//glViewport(0, 0, RENDER_WIDTH, RENDER_HEIGHT);
	//glPopAttrib();
}
